package edu.ou.herbarium.threads;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;

import edu.ou.herbarium.wsclient.Specimen;

public class DataLoader extends Thread{
	private static int SOURCE_NUMBER_TEMP = 12;
	private ShareData s;
	private int counter;
	private int spanCounter = 0;
	
	private Socket connectionSocket = null;
	
	public DataLoader(ShareData s, Socket socket) {
		this.connectionSocket = socket;
		this.s = s;
	}
	public void run() {
		String clientSentence, capitalizedSentence;
		try {
			BufferedReader inFromClient = new BufferedReader(
					new InputStreamReader(connectionSocket.getInputStream()));
		
			DataOutputStream outToClient = new DataOutputStream(
					connectionSocket.getOutputStream());
			
			while (true) {
				System.out.println("receiving");
				clientSentence = inFromClient.readLine();
				if(clientSentence==null||clientSentence.equals("")){
					System.out.println("empty");
					continue;
				}
				System.out.println("Received: " + clientSentence);
				if (clientSentence.equals("BYE"))
				{
					if(spanCounter==ShareData.TIME_SPAN){
						System.out.println("data loader exit");
						s.setShareChar(null);
						outToClient.close();
						inFromClient.close();
						connectionSocket.close();
						return;
					} 
					s.setShareChar(null);
					spanCounter++;
					continue;
				}
				String [] dataArray = clientSentence.split(",");
				Specimen spec = new Specimen();
				
				spec.setBarcode(dataArray[0].split(":")[1]);
				spec.setTempData(clientSentence.split(",")[9].split(":")[1]);
				spec.setStateProvince(clientSentence.split(",")[7].split(":")[1]);
				spec.setTown(clientSentence.split(",")[12].split(":")[1]);
				spec.setCounty(clientSentence.split(",")[8].split(":")[1]);
				spec.setGenus(clientSentence.split(",")[5].split(":")[1]);
				spec.setFamily(clientSentence.split(",")[6].split(":")[1]);
				spec.setSpecificEpithet(clientSentence.split(",")[3].split(":")[1]);
				spec.setCountry("United States");
				spec.setDarwinCountry("United States");
				spec.setSheetNotes("This is a test sheet note.");
				spec.setScientificName(clientSentence.split(",")[2].split(":")[1]);
				s.setShareChar(spec);
				counter++;
			}
			

				
				
				
			
		} catch (IOException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}
}
